﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpIM.Http
{
    public class JsonPayload : IRequestPayload
    {
        public string Value { get; internal set; }

        JObject _obj;
        public JObject objectValue
        {
            get
            {
                return _obj ?? (_obj = JsonConvert.DeserializeObject(Value) as JObject);
            }
        }
        string[] _props;
        public string[] Properties
        {
            get
            {

                return _props ?? (_props = objectValue.Properties().Select(x => x.Name).ToArray());
            }
        }

        public object ReadProperty(string name, Type parameterType)
        {
            if (objectValue == null)
                return null;
            if (parameterType.IsArray)
            {
                return objectValue;
            }
            var obj = objectValue as JObject;

            var value = obj.GetValue(name, StringComparison.OrdinalIgnoreCase);
            if (value == null)
                return value;
            return value.ToObject(parameterType);
        }
    }
}
